<template>
  <div class="container">
    <div class="app-container">
      <div class="topBtn">
        <el-button type="primary" size="small" @click="showDialog = true">
          新增角色
        </el-button>
      </div>

      <el-table :data="list" style="width: 100%">
        <el-table-column prop="name" label="角色" width="200" align="center">
          <template v-slot="{ row }">
            <el-input
              v-if="row.isEdit"
              size="mini"
              v-model="row.editRow.name"
            ></el-input>
            <span v-else>{{ row.name }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="启用" width="200" align="center">
          <template v-slot="{ row }">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
            <span v-else>{{
              row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "未知"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" align="center">
          <template v-slot="{ row }">
            <el-input
              v-model="row.editRow.description"
              type="textarea"
              size="mini"
              v-if="row.isEdit"
            ></el-input>
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" align="center">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="btnEditOk(row)">
                确认
              </el-button>
              <el-button size="mini" @click="row.isEdit = false"
                >取消</el-button
              >
            </template>
            <template v-else>
              <el-button
                type="text"
                size="mini"
                @click="assignPermission(row.id)"
              >
                分配权限
              </el-button>
              <el-button
                type="text"
                size="mini"
                style="margin-right: 10px"
                @click="btnEditRow(row)"
              >
                编辑
              </el-button>
              <el-popconfirm
                title="确定删除吗？"
                @onConfirm="delRoleFn(row.id)"
              >
                <el-button type="text" slot="reference" size="mini">
                  删除
                </el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagStyle">
        <el-pagination
          :total="pageParams.total"
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          layout="prev, pager, next"
          @current-change="changePage"
        >
        </el-pagination>
      </div>
    </div>
    <!-- 新增角色弹层 -->
    <el-dialog
      @close="cancel"
      title="新增角色"
      :visible.sync="showDialog"
      width="500px"
    >
      <el-form
        ref="roleForm"
        :model="roleForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="roleForm.state"
          ></el-switch>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            size="mini"
            type="textarea"
            :rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="addBtn()">
                确定
              </el-button>
              <el-button size="mini" @click="cancel()">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 权限分配弹层 -->
    <el-dialog title="分配权限" :visible.sync="dialogVisible">
      <el-tree
        ref="roleDialog"
        node-key="id"
        check-strictly
        :data="permissionList"
        :default-checked-keys="selectArray"
        :props="defaultProps"
        default-expand-all
        show-checkbox
      >
      </el-tree>
      <el-row type="flex" justify="center">
        <el-col :span="6">
          <el-button size="mini" @click="dialogVisible = false">
            取 消
          </el-button>
          <el-button
            size="mini"
            type="primary"
            @click="roleAssiginPermission()"
          >
            确 定
          </el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getPermissionListApi } from "@/api/permission";
import {
  getRoleList,
  addRoleApi,
  editRoleApi,
  delRoleApi,
  assignPermissionApi,
  getRoleDDetail,
} from "@/api/role";
import { transListToTreeData } from "@/utils";
export default {
  name: "Role",
  data() {
    return {
      list: [], // 每页的数据，不是全部的
      // 把分页信息放在一个对象中，好管理，发送请求的时候也可以直接用
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0, // 总条数
      },
      showDialog: false, // 弹层显示状态
      // 新增角色表单数据
      roleForm: {
        name: "",
        description: "",
        state: 0,
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
        description: [
          {
            required: true,
            message: "角色描述不能为空",
            trigger: "blur",
          },
        ],
      },
      dialogVisible: false, // 分配权限弹层状态
      permissionList: [], // 分配权限弹层的权限树状图
      defaultProps: {
        children: "children",
        label: "name",
      },
      roleId: null, // 角色的id
      selectArray: [], //当前选中的节点
    };
  },
  created() {
    this.getRoleList();
  },

  methods: {
    async getRoleList() {
      const res = await getRoleList(this.pageParams);
      this.list = res.rows;
      this.pageParams.total = res.total;
      // 针对每一行数据添加一个编辑标记
      this.list.forEach((item) => {
        // item.isEdit = false;
        // 数据响应式的问题，数据变化视图需要更新
        // 添加的动态属性 不具备响应式特点
        // this.$set(目标对象，"属性名称"，初始值) 可以针对目标对象 添加的属性 添加响应式
        this.$set(item, "isEdit", false);
        // 初始化时定义缓存数据，用于点击编辑数据回显到表格的。
        this.$set(item, "editRow", {
          name: item.name,
          state: item.state,
          description: item.description,
        });
      });
      // console.log(this.list);
    },
    // 换页
    changePage(val) {
      console.log(val);
      this.pageParams.page = val;
      this.getRoleList(this.pageParams);
    },
    // 新增角色表单中的确定按钮
    addBtn() {
      this.$refs.roleForm.validate(async (isOk) => {
        if (isOk) {
          await addRoleApi(this.roleForm);
          this.$message.success("新增角色成功");
          this.getRoleList();
          this.cancel();
        }
      });
    },
    // 取消按钮
    cancel() {
      this.showDialog = false;
      this.$refs.roleForm.resetFields(); // 重置表单
    },
    // 编辑角色
    btnEditRow(row) {
      console.log(row);
      row.isEdit = true; // 改变行的编辑状态
      row.editRow.name = row.name;
      row.editRow.state = row.state;
      row.editRow.description = row.description;
    },
    // 编辑角色中的确认
    async btnEditOk(row) {
      await editRoleApi({ ...row.editRow, id: row.id });
      this.$message.success("修改成功");
      Object.assign(row, { ...row.editRow, isEdit: false });
    },
    // 删除
    async delRoleFn(id) {
      // console.log(id);
      await delRoleApi(id);
      this.$message.success("删除成功");
      // 当前页面只有一条数据的时候，删除后页码应该减一
      if (this.list.length === 1) {
        this.pageParams.page--;
      }
      this.getRoleList();
    },
    // 分配权限
    async assignPermission(id) {
      // 这里获取的是弹层里的树状图
      const res = await getPermissionListApi();
      this.permissionList = transListToTreeData(res, 0);
      // console.log(this.permissionList);
      // 这里获取的是单个的详情，从这里获取已经有的权限进行数据回显
      this.roleId = id;
      // console.log(this.roleId);
      const { permIds } = await getRoleDDetail(id);
      console.log(permIds);
      this.selectArray = permIds;
      this.dialogVisible = true;
      //
    },

    // 分配权限里面的确定按钮
    async roleAssiginPermission() {
      await assignPermissionApi({
        id: this.roleId,
        permIds: this.$refs.roleDialog.getCheckedKeys(),
      });
      this.$message.success("分配权限成功");
      this.dialogVisible = false;
    },
  },
};
</script>
<style scoped>
.topBtn {
  padding: 10px;
}
.pagStyle {
  display: flex;
  justify-content: flex-end;
}
</style>
